<script setup>
import ListContainer from "@/components/AdminConponents/ListContainer.vue";
import {Search} from "@element-plus/icons-vue";
import {ref, computed} from "vue";
import {categoryListAPI, categoryDeleteAPI} from "@/api/AdminApi/category.js";
import 'element-plus/theme-chalk/el-message.css'
import 'element-plus/theme-chalk/el-message-box.css'
import {ElMessage, ElMessageBox} from "element-plus";
import AddOrEdit from "@/views/AdminViews/GameCategoryManagement/List/components/AddOrEdit.vue";

const categoryList = ref([]) // 游戏分类列表
const total = ref(0) // 总条数
const loading = ref(false)
const checkList = ref([])

// 定义请求参数对象
const params = ref({
  page: 1, // 当前页
  pageSize: 20, // 当前生效的每页条数
  name: null, // 分类名称
  sort: 0 // 排序方式
})

// 基于params参数，获取游戏分类列表
const getCategoryList = async () => {
  loading.value = true

  const res = await categoryListAPI(params.value)
  categoryList.value = res.records
  total.value = res.total

  loading.value = false
}
getCategoryList()

// 处理分页逻辑
const onSizeChange = (size) => {
  // console.log('当前每页条数', size)
  // 只要是每页条数变化了，那么原本正在访问的当前页意义不大了，数据大概率已经不在原来的那一页
  // 重新从第一页渲染即可
  params.value.page = 1
  params.value.pageSize = size
  // 基于最新的当前页和每页条数，渲染数据
  getCategoryList()
}

const onCurrentChange = (page) => {
  params.value.page = page
  // 基于最新的当前页，渲染数据
  getCategoryList()
}

// 搜索
const search = () => {
  getCategoryList()
}

// 计算页数
const totalPages = computed(() => {
  return Math.ceil(total.value / params.value.pageSize)
})

// 上一页
const goToPreviousPage = () => {
  if (params.value.page > 1) {
    params.value.page -= 1;
  }
  getCategoryList()
}

// 下一页
const goToNextPage = () => {
  if (params.value.page < totalPages.value) {
    params.value.page += 1;
  }
  getCategoryList()
}

// 更新管理员状态
const handleDelete = async (id, name) => {
  await ElMessageBox.confirm(`你确认删除${name}分类吗`, '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  const res = await categoryDeleteAPI([id])
  if (res.code === 1) {
    ElMessage.success("删除成功")
    getCategoryList()
  } else {
    ElMessage.error(res.msg)
  }
}

// 处理选中的分类
const handleSelectionChange = (val) => {
  checkList.value = val
}

// 选择框改变
const stateChange = () => {
  getCategoryList()
}

// 批量删除
const deleteBatch = async () => {
  if (checkList.value.length === 0) {
    ElMessage.warning("请选择要删除的分类！")
    return
  }
  await ElMessageBox.confirm(`你确认删除所选分类吗，该操作无法撤销`, '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  const ids = checkList.value.map(item => item.id)
  const res = await categoryDeleteAPI(ids)
  if (res.code === 1) {
    ElMessage.success("删除成功")
    getCategoryList()
  } else {
    ElMessage.error(res.msg)
  }
}

// 新增和修改
// dialog对话框参数
const dialogVisible = ref(false)
const dialogParams = ref({
  title: null,
  category: null
})
// 新增
const addCategory = () => {
  dialogParams.value.category = null
  dialogParams.value.title = "添加游戏分类"
  dialogVisible.value = true
}

// 修改
/* eslint-disable no-unused-vars */
const handleEdit = ({createTime, updateTime, createUserId, updateUserId, ...category}) => {
  dialogParams.value.category = category
  dialogParams.value.title = "修改游戏分类"
  dialogVisible.value = true
}

// 对话框关闭时数据清除
const handleClose = () => {
  dialogVisible.value = false
  dialogParams.value.category = null
  getCategoryList()
}
</script>

<template>
  <ListContainer>
    <template #headerLeft>
      <el-input
          v-model="params.name"
          placeholder="请输入分类名称"
          class="input-with-select">
        <template #append>
          <el-button @click="search" :icon="Search" />
        </template>
      </el-input>
      <el-select v-model="params.sort" placeholder="排序方式" @change="stateChange" style="width: 150px;">
        <el-option label="按修改时间" :value="0" />
        <el-option label="按购买次数" :value="1" />
      </el-select>
    </template>
    <template #headerRight>
      <el-button type="danger" @click="deleteBatch" style="width: 100px;">
        <i class="iconfont icon-shanchu"></i>
        批量删除
      </el-button>
      <el-button type="primary" @click="addCategory" style="width: 100px;">
        <i class="iconfont icon-tianjia"></i>
        添加分类
      </el-button>
    </template>
    <template #body>
      <el-table
          :data="categoryList"
          v-loading="loading"
          @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="分类名称" />
        <el-table-column prop="updateTime" label="最后操作时间" />
        <el-table-column prop="buyTimes" label="购买次数"/>
        <el-table-column fixed="right" label="操作" width="140px">
          <template #default="{ row }">
            <el-button type="success" @click="handleEdit(row)" size="small">编辑</el-button>
            <el-button type="danger" @click="handleDelete(row.id, row.name)" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template #footerLeft>
      <el-button
          type="info"
          :disabled="params.page === 1"
          @click="goToPreviousPage">
        上一页
      </el-button>
      <el-button
          type="info"
          :disabled="params.page === totalPages"
          @click="goToNextPage">
        下一页
      </el-button>
    </template>
    <template #footerRight>
      <el-pagination
          v-model:current-page="params.page"
          v-model:page-size="params.pageSize"
          :page-sizes="[5, 10, 20, 40]"
          layout="total, sizes, pager, jumper"
          :total="total"
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
      />
    </template>
  </ListContainer>
  <AddOrEdit v-model="dialogVisible" :dialogParams @close="handleClose"></AddOrEdit>
</template>

<style scoped>

</style>
